//
//  YRComposeViewController.swift
//  YR 微博
//
//  Created by cyr on 15/10/20.
//  Copyright © 2015年 cyr. All rights reserved.
//

import UIKit

class YRComposeViewController: UIViewController , UITextViewDelegate{
    
    private lazy var emoticonVC: YREmoticonViewController = YREmoticonViewController { [weak self] (emoticon) -> () in
        self?.textView.insertEmoticon(emoticon)
    }
    
    
    // MARK: - UITextViewDelegate
    func textViewDidChange(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }

    /**
    表情键盘控制器
    */
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        addKeyboardOberserver()
        
    }
    
    deinit {
        removeKeyboardOberserver()
    }
   
    func keyboardChanged(n:NSNotification) {
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        toolBarBottonCons?.constant = -(UIScreen.mainScreen().bounds.height - rect.origin.y)

        toolBarBottonCons?.constant = -rect.size.height
        
        // 动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    /**
    添加键盘通知
    */
    private func addKeyboardOberserver() {
         NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    /**
    移除键盘通知
    */
    private func removeKeyboardOberserver() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        textView.becomeFirstResponder()
    }
    
    // MARK: - 搭建界面
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        
        prepareNav()
        prepareToolBar()
        prepareTextView()
    }
    
    /**
    准备导航栏
    */
    private func prepareNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 标题栏
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 44))
//        titleView.backgroundColor = UIColor.blueColor()
        
        let titleLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15)
        titleLabel.text = "发微博"
        titleView.addSubview(titleLabel)
        
        let nameLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 13)
        nameLabel.text = YRUserAccount.sharedAccount?.name ?? ""
        titleView.addSubview(nameLabel)
        
        navigationItem.titleView = titleView
        
        // 标题栏自动布局
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
    }
    
    /**
    准备文本框
    */
    private func prepareTextView() {
        
        view.addSubview(textView)
        
        textView.backgroundColor = UIColor.whiteColor()
        
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil)
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
    }
    
 
    /**
    准备工具栏
    */
    private func prepareToolBar() {
        
        view.addSubview(toolBar)
        // 设置背景颜色
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        view.addSubview(toolBar)
        
        let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        toolBarBottonCons = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        // 准备添加按钮
        let itemSettings = [["imageName":"compose_toolbar_picture"],
        ["imageName":"compose_trendbutton_background"],
        ["imageName":"compose_mentionbutton_background"],
        ["imageName":"compose_emoticonbutton_background","action" : "inputEmoticon"],
        ["imageName":"compose_addbutton_background"]]
        
        // 便利数组添加按钮
        var items = [UIBarButtonItem]()
        for dict in itemSettings {
            
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["action"]))
            
            // 追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        items.removeLast()
        
        toolBar.items = items
    }
    
    private var toolBarBottonCons: NSLayoutConstraint?
    

    
    /**
    懒加载
    */
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    lazy var textView: UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.alwaysBounceVertical = true
        tv.delegate = self
        
        // 拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return tv
        
        }()
    /// 占位标签
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.text = "分享新鲜事..."
        label.textColor = UIColor.lightGrayColor()
        label.sizeToFit()
        
        return label
    }()
    


    // MARK: - 监听方法
    /**
    关闭
    */
    func close() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    /**
    *  发布微博
    */
    func sendStatus() {
        
    YRNetworkTools.sharedTools.sendStatus(textView.emoticonText) { (result, error) -> () in
        print(result)
        print(error)
        }
        
    }
   
    
    func inputEmoticon() {
  
        print("选择表情 \(textView.inputView)")
        // 0. 注销键盘通知
        removeKeyboardOberserver()
        
        // 1. 关闭键盘
        textView.resignFirstResponder()
        
        // 2. 设置输入键盘
        textView.inputView = (textView.inputView == nil) ? emoticonVC.view : nil
        
        // 3. 重新注册通知
        addKeyboardOberserver()
        
        // 4. 激活键盘
        textView.becomeFirstResponder()
    }
}
